const fs = require('fs');
const path = require('path');
const dotenv = require('dotenv');
const dotenvExpand = require('dotenv-expand');

const NODE_ENV = process.env.NODE_ENV || 'development';

const os = require('os');

function getNetworkIp() {
  let needHost = ''; // 打开的host
  try {
    // 获得网络接口列表
    let network = os.networkInterfaces();
    // console.log("network",network)
    for (let dev in network) {
      let iface = network[dev];
      for (let i = 0; i < iface.length; i++) {
        let alias = iface[i];
        if (
          alias.family === 'IPv4' &&
          alias.address !== '127.0.0.1' &&
          !alias.internal
        ) {
          needHost = alias.address;
          // console.log("alias.address",alias.address)
        }
        // console.log("alias",alias)
      }
    }
  } catch (e) {
    needHost = 'localhost';
  }
  return needHost;
}

function resolve(dir) {
  return path.join(__dirname, '../../', dir); // .env文件的位置，项目根目录下
}

const envFile = resolve('.env');

const dotenvFiles = [
  `${envFile}.${NODE_ENV}.local`,
  `${envFile}.${NODE_ENV}`,
  // Don't include `.env.local` for `test` environment
  // since normally you expect tests to produce the same
  // results for everyone
  NODE_ENV !== 'test' && `${envFile}.local`,
  envFile,
].filter(Boolean);

dotenvFiles.forEach((dotenvFile) => {
  if (fs.existsSync(dotenvFile)) {
    dotenvExpand.expand(
      dotenv.config({
        path: dotenvFile,
      })
    );
  }
});

const reg = /^(MICRO_)/;
const raw = Object.keys(process.env)
  .filter((key) => reg.test(key))
  .reduce((env, key) => {
    env[key] = process.env[key];
    if (
      process.env['MICRO_TRANS_LOCALHOST_ENABLE'] === 'true' &&
      env[key].indexOf('localhost') > -1
    ) {
      // @todo 替换localhost为本机ip
      console.log('replace localhost');
      env[key] = env[key].replace('localhost', getNetworkIp());
    }
    return env;
  }, {});

const stringified = Object.keys(raw).reduce((env, key) => {
  env[key] = JSON.stringify(raw[key]);
  return env;
}, {});

module.exports = {
  raw,
  stringified,
};
